package com.sammy.appmonitor.contentprovider;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.provider.BaseColumns;
import com.sammy.utils.MyLog;

import com.sammy.appmonitor.contentprovider.MyContract.MessagesOut;
import com.sammy.appmonitor.main.MainActivity;
import com.sammy.utils.MyUtils;

public class TableMessagesOut {
	public static final String TAG = "TableMessagesOut.";

	public static RecordMessagesOut getFirstRecord(Context context){
		RecordMessagesOut result = null;
		try{
		String[] projection =
			{ 
				BaseColumns._ID,
				MessagesOut.MESSAGE,
				MessagesOut.RECORD_TIME
			};
		String sortOrder = BaseColumns._ID;
		Cursor cursor = context.getContentResolver().query(
				MessagesOut.CONTENT_URI,//content uri for this table 
				projection,//projection 
				null,//selection clause
				null,//selection args 
				sortOrder);//sort order		
		if (cursor.moveToFirst()) {
			result = new RecordMessagesOut();
			
			int indexMessage = cursor.getColumnIndex(MessagesOut.MESSAGE);
			String message = (String)cursor.getString(indexMessage);						
			result.setMessage(message);
			
			int indexId = cursor.getColumnIndex(BaseColumns._ID);
			int id = cursor.getInt(indexId);
			result.setId(id);
			
			int indexRecordTime = cursor.getColumnIndex(MessagesOut.RECORD_TIME);
			String recordTime = cursor.getString(indexRecordTime);					
			result.setRecordTime(recordTime);
		}
		cursor.close();
		}catch(Exception e){
			MyLog.e(MainActivity.PROCESS_TAG,TAG+"getFirstRecord exception: " + e.getMessage());
		}
		return result;
	}
	
	public static void deleteRecord(Context context, int id){
		try{
		String selectionClause = BaseColumns._ID + " = " + id;
		//String[] selectionArgs = {""+id};
		// Deletes the words that match the selection criteria
		int rowsDeleted = context.getContentResolver().delete(
		    MessagesOut.CONTENT_URI,   // the user dictionary content URI
		    selectionClause,                    // the column to select on
		    null//selectionArgs                      // the value to compare to
		);
		MyLog.d(MainActivity.PROCESS_TAG,TAG+"deleteRecord, rowsDeleted = " + rowsDeleted);
		}catch(Exception e){
			MyLog.e(TAG,"deleteRecord exception: " + e.getMessage());
		}

	}
	
	public static void insertRecord(Context context, RecordAppHistory message) {
		try{
		ContentValues values = new ContentValues();
		values.put(MessagesOut.MESSAGE, message.getContent());
		values.put(MessagesOut.RECORD_TIME, MyUtils.getFormatedCurrentTime());		
		context.getContentResolver().insert(MessagesOut.CONTENT_URI, values);
		}catch(Exception e){
			MyLog.e(MainActivity.PROCESS_TAG,TAG+"insertRecord exception: " + e.getMessage());
		}

	}

}
